package uia.alumni.web;


import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



/**
 * The Controller is the only servlet with a url-mapping. It
 * serves as a sort of gate-keeper for the application.
 *
 * @author Even Åby Larsen (even.larsen@uia.no)
 */
public class Controller extends HttpServlet implements Constants {
    public static final long serialVersionUID = 1;


    /**
     * Handle get requests by calling execute()
     *
     * @param req the request object
     * @param resp the response object
     * @throws IOException if writing the response fails.
     * @throws ServletException if anything else fails and graceful recovery is impossible.
     */
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        execute(req, resp);
    }


    /**
     * Handle post requests by calling execute()
     *
     * @param req the request object
     * @param resp the response object
     * @throws IOException if writing the response fails.
     * @throws ServletException if anything else fails and graceful recovery is impossible.
     */
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        execute(req, resp);
    }


    /**
     * This is the central point of control in the Research Assistant application.
     * It handles all http requests. The http request is examined to determine which
     * command to execute. If no command is specified the command to display the start
     * page is executed.
     * 
     * @param httpReq The request object.
     * @param response The response object.
     * @throws IOException DOCUMENT WHEN!!
     * @throws ServletException DOCUMENT WHEN!!
     */
    protected void execute(HttpServletRequest request,
                                  HttpServletResponse response)
            throws ServletException, IOException {

        // all pages are encoded in utf-8
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        log("\n=============================================="
                +"\nStart processing request "
                + request.getRequestURL());

        // get the command name from the url
        String command = request.getServletPath();
        // remove leading '/'
        if (command.startsWith("/"))
            command = command.substring(1);
        // strip off extension
        int pos = command.lastIndexOf(".do");
        if (pos > 0)
            command = command.substring(0, pos);
        else command = Home.SERVLET_NAME;

        // forward to the command
        ServletContext context = getServletContext();
        log("Dispatching to "+command);
        try {
            RequestDispatcher rd = context.getNamedDispatcher(command);
            if (rd == null)
                throw new DispatchException("Can't dispatch to non-existant command: "+command);
            rd.forward(request, response);
        }
        catch (DispatchException e) {
            log("Dispatch failed", e);
            RequestDispatcher rd = context.getNamedDispatcher(Home.SERVLET_NAME);
            rd.forward(request, response);
        }
    }
}
